/**
 * 步骤7测试：确认预约（onClickSubmit提交）
 */

import { fileURLToPath } from 'node:url'
import { dirname, join } from 'node:path'
import { HttpSession } from '../src/main/request/http-session'
import { getPageParser } from '../src/main/automation/page-parser'
import { loadConfig } from '../src/main/config/index'
import { setupLogger } from '../src/main/logger/index'
import { writeFile, mkdir, readFile } from 'node:fs/promises'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const projectRoot = join(__dirname, '..')

const BASE_URL = 'https://abs1.td.gov.hk/tdab2/tdabs_external/AdminServlet_tchinese'
const SNAPSHOT_DIR = join(projectRoot, 'test-steps-snapshots')

async function saveSnapshot(name: string, html: string, metadata: any = {}) {
  await mkdir(SNAPSHOT_DIR, { recursive: true })
  const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
  const filename = `${timestamp}_step07_${name}.html`
  const filepath = join(SNAPSHOT_DIR, filename)
  await writeFile(filepath, html, 'utf8')
  console.log(`  ✓ 快照已保存: ${filename}`)
  return filepath
}

async function loadStep6Result() {
  const files = await import('node:fs/promises')
  const dir = await files.readdir(SNAPSHOT_DIR)
  const step6Files = dir.filter(f => f.includes('step06_confirm') && f.endsWith('.html')).sort().reverse()
  
  if (step6Files.length === 0) {
    throw new Error('未找到步骤6的快照文件，请先运行步骤6测试')
  }
  
  const latestFile = join(SNAPSHOT_DIR, step6Files[0])
  const html = await readFile(latestFile, 'utf8')
  const parser = getPageParser()
  const formFields = parser.extractFormFields(html, 'frmAppointment')
  
  return { html, formFields, filepath: latestFile }
}

function checkResultPage(html: string): { success: boolean, details: Record<string, boolean>, referenceNumber?: string } {
  const parser = getPageParser()
  const bookingResult = parser.parseBookingResult(html)
  const hasReference = bookingResult.success && bookingResult.data?.success && bookingResult.data.reference_number
  
  const checks = {
    isSubmitPage: html.includes('cmdSubmitAppointmentAction'),
    hasReferenceNumber: !!hasReference,
    hasSuccessMessage: html.includes('成功') || html.includes('參考編號') || html.includes('参考编号'),
    hasErrorMessage: html.includes('錯誤') || html.includes('错误') || html.includes('失敗') || html.includes('失败'),
    hasForm: html.includes('form') && html.includes('frmAppointment'),
  }
  
  console.log(`\n📄 结果页面检查`)
  console.log('─'.repeat(60))
  for (const [key, value] of Object.entries(checks)) {
    const icon = value ? '✓' : '✗'
    const label = key.replace(/([A-Z])/g, ' $1').trim()
    console.log(`  ${icon} ${label}`)
  }
  
  if (hasReference) {
    console.log(`\n  📋 参考编号: ${bookingResult.data!.reference_number}`)
  }
  
  return { 
    success: checks.isSubmitPage && (checks.hasReferenceNumber || checks.hasSuccessMessage),
    details: checks,
    referenceNumber: hasReference ? bookingResult.data!.reference_number : undefined,
  }
}

async function testStep7() {
  console.log('步骤7测试：确认预约（onClickSubmit提交）')
  console.log('='.repeat(60))
  
  await loadConfig()
  await setupLogger()
  
  // 加载步骤6的结果
  console.log('\n📂 加载步骤6结果...')
  const step6Result = await loadStep6Result()
  const step6Fields = step6Result.formFields.success && step6Result.formFields.data ? step6Result.formFields.data : {}
  console.log(`  从步骤6提取字段数: ${Object.keys(step6Fields).length}`)
  
  const session = new HttpSession()
  
  // 子步骤7.1: 提交预约（调用onClickSubmit -> cmdSubmitAppointmentAction）
  console.log('\n子步骤7.1: 提交预约（onClickSubmit -> cmdSubmitAppointmentAction）')
  console.log('─'.repeat(60))
  
  const payload: Record<string, string> = {
    ...step6Fields,
    storedAppointmentOperation: 'A',
    timestamp: Date.now().toString(),
  }
  
  const url = `${BASE_URL}?cmd=cmdSubmitAppointmentAction`
  console.log(`请求: POST ${url}`)
  console.log(`  载荷字段数: ${Object.keys(payload).length}`)
  
  const response = await session.postForm(url, payload, `${BASE_URL}?cmd=cmdConfirmAppointment`)
  const check = checkResultPage(response.body)
  
  await saveSnapshot('submit_result', response.body, {
    step: '7.1',
    url: response.url,
    status: response.status,
    check,
    referenceNumber: check.referenceNumber,
  })
  
  if (check.details.hasReferenceNumber) {
    console.log(`\n✓ 步骤7成功：预约提交成功！`)
    console.log(`  参考编号: ${check.referenceNumber}`)
  }
  else if (check.details.hasErrorMessage) {
    console.log(`\n⚠️  步骤7警告：预约提交后返回错误信息`)
    console.log('  这可能是业务逻辑错误（如时段已被占用），但流程是正确的')
  }
  else {
    console.log(`\n⚠️  步骤7警告：无法确定预约是否成功`)
  }
  
  console.log(`\n📁 快照目录: ${SNAPSHOT_DIR}`)
}

testStep7().catch((error) => {
  console.error('\n❌ 测试失败:', error)
  process.exit(1)
})

